package com.zhixue.auth.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhixue.auth.feignclient.CheckCodeClient;
import com.zhixue.auth.ucenter.mapper.XcUserMapper;
import com.zhixue.auth.ucenter.model.dto.*;
import com.zhixue.auth.ucenter.model.po.XcUser;
import com.zhixue.auth.ucenter.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Auther: 李 力
 * @Date: 2025/5/12
 * @Description: com.zhixue.auth.ucenter.service.impl
 * @version: 1.0
 */
@Service(value = "password_authService")
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    private XcUserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private CheckCodeClient checkCodeClient;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //查询数据库
        String userName = authParamsDto.getUsername();
        if (StringUtils.isEmpty(userName)) {
            throw new RuntimeException("用户名为空");
        }
        LambdaQueryWrapper<XcUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(XcUser::getUsername, userName);
        XcUser xcUser = userMapper.selectOne(wrapper);
        if (xcUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //从数据库获取的密码
        String passwordDB = xcUser.getPassword();
        //从参数回去密码
        String passwordParam = authParamsDto.getPassword();
        //校验密码
        boolean matches = passwordEncoder.matches(passwordParam, passwordDB);
        if (!matches) {
            throw new RuntimeException("密码错误");
        }
        //校验验证码
        String checkcodekey = authParamsDto.getCheckcodekey();
        String checkcode = authParamsDto.getCheckcode();
        if (StringUtils.isEmpty(checkcodekey) || StringUtils.isEmpty(checkcode)) {
            throw new RuntimeException("验证码为空");
        }
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if (verify == null || !verify) {
            throw new RuntimeException("验证码错误");
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);
        return xcUserExt;
    }
}
